<?php

class App_Auth_Adapter_Doctrine implements Zend_Auth_Adapter_Interface
{
	protected $_model;
	
	protected $_identityColumn;
	protected $_credentialColumn;
	protected $_identity;
	protected $_credential;
	
	public function authenticate()
	{
		$findBy = 'findOneBy' . ucfirst($this->_identityColumn);
		$user = $this->_model->$findBy($this->_identity);
		if ($user){
			if ( $user->password == sha1($this->_credential . $user->salt) ){
				if( $user->status == 1){
					return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $user, array());
				}
				else {
					return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS, $user, array());
				}
			}
			else {
				return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, $user, array());
			}
		}
		else {
			return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, $user, array());
		}
	}
	
	public function setModel($model){
		if($model instanceof Doctrine_Record){
			$this->_model = $model;
		}
		elseif ( is_string($model) && class_exists($model) ){
			$this->_model = Doctrine_Core::getTable($model);
		}
	}
	
	public function setIdentityColumn($column){
		$this->_identityColumn = $column;
	}
	
	public function setCredentialColumn($column){
		$this->_credentialColumn = $column;
	}
	
	public function setIdentity($identity){
		$this->_identity = $identity;
	}
	
	public function setCredential($credential){
		$this->_credential = $credential;
	}
	
}